package com.iflytek.springboot_medicine.controller;

import com.iflytek.springboot_medicine.entity.Category;
import com.iflytek.springboot_medicine.pojo.ResponseMessage;
import com.iflytek.springboot_medicine.pojo.PageResultPojo;
import com.iflytek.springboot_medicine.service.impl.CategoryServiceImpl;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    private final CategoryServiceImpl categoryService;

    public CategoryController(CategoryServiceImpl categoryService) {
        this.categoryService = categoryService;
    }

    @RequestMapping("/findAllCategory")
    public ResponseMessage<PageResultPojo<Category>> findAllUser(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name) {
        // 2. 调用 Service 层进行分页查询
        Page<Category> userPage = categoryService.findCategory(name, pageNum, pageSize);
        // 3. 封装分页结果
        PageResultPojo<Category> pageResult = new PageResultPojo<>(
                userPage .getTotalElements(), // 总条数
                pageSize,                   // 每页条数
                pageNum,                    // 当前页码
                userPage .getContent()       // 当前页的数据
        );
        return ResponseMessage.success(pageResult);
    }

    /**
     * 删除类别
     * @param id
     * @return
     */
    @RequestMapping("/deleteType/{id}")
    public ResponseMessage deleteUser(@PathVariable int id) {
        if (id > 0){
            categoryService.deleteCategory(id);
        }
        return ResponseMessage.success();
    }

    /**
     * 批量删除
     */
    @RequestMapping("/deleteBatchType")
    public ResponseMessage getUserById(@RequestBody List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return ResponseMessage.error("删除失败");
        }
        categoryService.deleteAllInBatch(ids);
        return ResponseMessage.success();
    }


    /**
     * 增加药材类别
     * @param category
     * @return
     */
    @RequestMapping("/addType")
    public ResponseMessage<Category> addUser(@RequestBody Category category) {
        if (category == null) {
            return ResponseMessage.error("增加失败");
        }
        categoryService.addCategory(category);
        return ResponseMessage.success(category);
    }

    /**
     * 更新药材类别信息
     * @param category
     * @return
     */
    @RequestMapping("/updateType")
    public ResponseMessage<Category> updateUser(@RequestBody Category category) {
        if (category == null) {
            return ResponseMessage.error("更新失败");
        }
        categoryService.updateCategory(category);
        return ResponseMessage.success(category);
    }
}
